package com.nuliji.tools.shiro;

import com.alibaba.fastjson.JSON;
import com.nuliji.tools.Response;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * Created by GaoJie on 2017/07/31.
 */
public class RoleFilter extends RolesAuthorizationFilter {

    private static final Logger logger = LoggerFactory.getLogger(RoleFilter.class);

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        if(!subject.isAuthenticated() && !subject.isRemembered()){
            logger.debug("not login");
            return false;
        }
        String[] rolesArray = (String[])((String[])mappedValue);
        if(rolesArray != null && rolesArray.length != 0) {
            subject.getPrincipals();
            Set<String> roles = CollectionUtils.asSet(rolesArray);
            for(String role: roles){
                if(subject.hasRole(role)) return true;
                logger.debug("not {}", role);
            }
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        saveRequest(request);
        response.setCharacterEncoding("UTF-8");

        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        try {
            response.getWriter().write(JSON.toJSONString( new Response(101, "未登录", null)));
        } finally {
        }
        return false;
    }
}
